<template>
  <div class="goods-sku">
    <dl v-for="item in goods.specs" :key="item.id">
      <dt>{{item.name}}</dt>
      <dd>
        <template v-for="val in item.values" :key="val.name">
          <img @click="changeSku(item, val)" v-if="val.picture" :class="{selected:val.selected}" :src="val.picture" :title="val.name" alt="">
          <span @click="changeSku(item, val)" v-else :class="{selected:val.selected}">{{val.name}}</span>
        </template>
      </dd>
    </dl>
  </div>
</template>
<script>

import powerSet from '@/vendor/power-set'

const spliter = '🌟'
// 得到一个路径字典对象
const getPathMap = (skus) => {
  // 1.得到所有的sku集合 props.goods.skus
  // 2.从所有的sku中筛选出有效的sku
  // 3.根据有效的sku使用power-set算法得到子集
  // 4.根据子集往路径字典对象中存储 key-value
  const pathMap = {}
  skus.forEach(sku => {
    if (sku.inventory > 0) {
      // 计算当前又库存的sku的子集
      // [1,2,3] ==> [[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]
      // 可选值数组
      const valueArr = sku.specs.map(val => val.valueName)
      // 可选值数组 子集
      const valueArrPowerSet = powerSet(valueArr)

      // console.log(valueArrPowerSet)
      // 遍历子集，往pathMap插入数据
      valueArrPowerSet.forEach(arr => {
        // 根据arr得到字符串的key，约定key是：['蓝色','美国'] ===> '蓝色*美国'
        const key = arr.join(spliter)
        if (pathMap[key]) {
          pathMap[key].push(sku.id)
        } else {
          pathMap[key] = [sku.id]
        }
      })
    }
  })
  return pathMap
}

// 得到当前选中规格集合
const getSelectedValues = (specs) => {
  const arr = []
  specs.forEach(item => {
    // 选中的按钮对象
    const selectedval = item.values.find(val => val.selected)
    arr.push(selectedval ? selectedval.name : undefined)
  })
  return arr
}

// 更新按钮禁用状态
const updateDisabledStatus = (specs, pathMap) => {
  // 1.约定每一个按钮的状态由本身的disabled数据来控制
  console.log(specs)
  specs.forEach((item, i) => {
    const selectedValues = getSelectedValues(specs)
    item.values.forEach(val => {
      // 2.判断当前是否选中，是选中，不用判断
      if (val.selected) return false
      // 3.拿当前的值按照顺序套入选中的值数组
      selectedValues[i] = val.name
      // 4.剔除undefined数据，按照分隔符拼接key
      const key = selectedValues.filter(value => value).join(spliter)
      // 5.拿着key去路径字典中查找是否有数据，有可以点击，没有就禁用(true)
      val.disabled = !pathMap[key]
    })
  })
}

// 默认选中
// const initDefaultSelected = (goods, skuId) => {
//   // 1.找到sku信息
//   // 2.遍历每个按钮，按钮的值和sku记录的值相同，就选中
//   const sku = goods.skus.find(sku => sku.id === skuId)
//   goods.specs.forEach((item, i) => {
//     const val = item.values.find(val => val.name === sku.specs[i].valueName)
//     val.selected = true
//   })
// }

export default {
  name: 'GoodsSku',
  props: {
    goods: {
      type: Object,
      default: () => ({ specs: [], skus: [] })
    }
  },
  setup (props, { emit }) {
    const pathMap = getPathMap(props.goods.skus)

    updateDisabledStatus(props.goods.specs, pathMap)

    // 1.选中与取消选中，约定在每个按钮都拥有自己的选中状态数据
    const changeSku = (item, val) => {
      // 当按钮是禁用的阻止程序运行
      if (val.disabled) return false
      // 如果不是禁用正常运行
      if (val.selected) {
        val.selected = false
      } else {
        item.values.forEach(valItem => {
          valItem.selected = false
        })
        val.selected = true
      }
      // 点击按钮时：更新按钮禁用状态
      updateDisabledStatus(props.goods.specs, pathMap)
      // 将你选中sku
      const validSelectValues = getSelectedValues(props.goods.specs).filter(v => v)
      if (validSelectValues.length === props.goods.specs.length) {
        const skuIds = pathMap[validSelectValues.join(spliter)]
        const sku = props.goods.skus.find(sku => sku.id === skuIds[0])
        emit('change', {
          skuId: sku.id,
          price: sku.price,
          oldPrice: sku.oldPrice,
          inventory: sku.inventory,
          specsText: sku.specs.reduce((p, c) => `${p} ${c.name}: ${c.valueName}`, '').trim()
        })
      } else {
        emit('change', {})
      }
    }
    return { changeSku }
  }
}
</script>
<style scoped lang="less">
.sku-state-mixin () {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;
  &.selected {
    border-color: @xtxColor;
  }
  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}
.goods-sku {
  padding-left: 10px;
  padding-top: 20px;
  dl {
    display: flex;
    padding-bottom: 20px;
    align-items: center;
    dt {
      width: 50px;
      color: #999;
    }
    dd {
      flex: 1;
      color: #666;
      > img {
        width: 50px;
        height: 50px;
        object-fit: cover;
        min-width: auto;
        min-height: auto;
        .sku-state-mixin ();
      }
      > span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        padding: 0 20px;
        .sku-state-mixin ();
      }
    }
  }
}
</style>
